<?php

namespace App\Http\Controllers\Api;

use App\Blocks\User;
use App\Http\Controllers\Controller;
use App\Libs\Message;
use App\Models\ActivityAnswer;
use App\Models\WechatOpenplatformToken;
use EasyWeChat\Factory;
use EasyWeChat\OpenPlatform\Server\Guard;
use function GuzzleHttp\Psr7\build_query;
use Illuminate\Http\Request;

class WechatController extends Controller
{
    //发起授权
    public function openPlatformPreAuth(){
        $config = \Config::get('wechat.open_platform.default');
        $openPlatform = Factory::openPlatform($config);

        $pre = $openPlatform->getPreAuthorizationUrl(env('APP_URL').'/api/wechat/open-platform/callback');

        return view('preauth',['url' => $pre]);
    }

    public function openPlatform(){
        $config = \Config::get('wechat.open_platform.default');
        $openPlatform = Factory::openPlatform($config);

        $server = $openPlatform->server;
        \Log::debug(111111);
        // 处理授权成功事件
        $server->push(function ($message) use ($openPlatform){
            \Log::debug(2222);
            \Log::debug($message);
            $token = $openPlatform->handleAuthorize($message['AuthorizationCode']);
            \Log::debug($token);
        }, Guard::EVENT_AUTHORIZED);

        // 处理授权更新事件
        $server->push(function ($message) use ($openPlatform){
            \Log::debug(33333);
            \Log::debug($message);
            $token = $openPlatform->handleAuthorize($message['AuthorizationCode']);

            \Log::debug($token);
        }, Guard::EVENT_UPDATE_AUTHORIZED);

        // 处理授权取消事件
        $server->push(function ($message) {
            \Log::debug($message);
            \Log::debug(4444);
        }, Guard::EVENT_UNAUTHORIZED);

        return $server->serve();
    }

    //授权回调
    public function openPlatformPreAuthCallback(Request $request){
        $config = \Config::get('wechat.open_platform.default');
        $openPlatform = Factory::openPlatform($config);
        $res = $openPlatform->handleAuthorize();
        $appid = $res['authorization_info']['authorizer_appid'];
        $refresh_token = $res['authorization_info']['authorizer_refresh_token'];

        if(WechatOpenplatformToken::updateOrCreate(['appid' => $appid], ['appid' => $appid, 'refresh_token' => $refresh_token]) === false){
            return response('授权失败');
        }else{
            return response('授权成功');
        }
    }

    //事件监听
    public function openPlatformCallback($appid,Request $request){
        $wechat = WechatOpenplatformToken::where('appid', $appid)->first();
        if(!$wechat){
            return response('不存在改微信公众号的信息');
        }
        $config = \Config::get('wechat.open_platform.default');
        $openPlatform = Factory::openPlatform($config);
        $wechatApp = $openPlatform->officialAccount($wechat->appid, $wechat->refresh_token);

        $wechatApp->server->push(function ($message) {
            switch ($message['MsgType']) {
                case 'event':
                    return '收到事件消息';
                    break;
                case 'text':
                    return '收到文字消息';
                    break;
                case 'image':
                    return '收到图片消息';
                    break;
                case 'voice':
                    return '收到语音消息';
                    break;
                case 'video':
                    return '收到视频消息';
                    break;
                case 'location':
                    return '收到坐标消息';
                    break;
                case 'link':
                    return '收到链接消息';
                    break;
                case 'file':
                    return '收到文件消息';
                // ... 其它消息
                default:
                    return '收到其它消息';
                    break;
            }

        });

        return $wechatApp->server->serve();
    }

    //登录
    public function openPlatformLogin($appid, Request $request){
        $wechat = WechatOpenplatformToken::where('appid', $appid)->first();
        if(!$wechat){
            return response('不存在改微信公众号的信息');
        }
        $config = \Config::get('wechat.open_platform.default');
        $openPlatform = Factory::openPlatform($config);
        $wechatApp = $openPlatform->officialAccount($wechat->appid, $wechat->refresh_token);

        return $wechatApp->oauth->redirect(env('APP_URL').'/api/wechat/open-platform/login/callback/'.$wechat->appid.'?'.build_query($request->all()));
    }

    //登录回调
    public function openPlatformLoginCallback($appid, Request $request){
        $wechat = WechatOpenplatformToken::where('appid', $appid)->first();
        if(!$wechat){
            return response('登录失败');
        }
        $config = \Config::get('wechat.open_platform.default');
        $openPlatform = Factory::openPlatform($config);
        $wechatApp = $openPlatform->officialAccount($wechat->appid, $wechat->refresh_token);

        $userService = $wechatApp->oauth->user();
        $weixinUserInfo = $userService->getOriginal();


        if(!isset($weixinUserInfo['openid'])){
            Log::debug('不存在openid');
            Log::debug($weixinUserInfo);
            return response()->json(['code' => 0 , 'msg' => '登录失败']);
        }

        $userService = $wechatApp->user;
        $user = $userService->get($weixinUserInfo['openid']);

        $user = (object)$user;

        if(!$user->subscribe){
            return redirect("/follow?wid={$appid}");
        }

        $userData = [];
        $userData['nickname']       = isset($user->nickname) ? $user->nickname : '';
        $userData['headimgurl']     = isset($user->headimgurl) ? $user->headimgurl : '';
        $userData['openid']         = $user->openid;
        $userData['subscribe_time'] = isset($user->subscribe_time) ? date('Y-m-d H:i:s',$user->subscribe_time) : null;
        $userData['subscribe']      = isset($user->subscribe) ? $user->subscribe : null;
        $userData['sex']            = isset($user->sex)? $user->sex : 0 ;
        $userData['city']           = isset($user->city)? $user->city : 0 ;
        $userData['province']       = isset($user->province)? $user->province : 0 ;
        $userData['country']        = isset($user->country)? $user->country : 0 ;
        $userData['wechat_id']      = $wechat->id;
        $userData['create_time']    = date('Y-m-d H:i:s', time());
        $userData['invite_uid']     = $request->get('invite', 0);

        $userBlock = new User();

        if($userBlock->saveWechatUser($userData)){
            $userInfo = $userBlock->getActivityUserInfoByOpenid($userData['openid']);

            \Log::debug(json_encode($userInfo));
            $token = md5($userData['openid']);

            \Cache::put($token, $userInfo, 60);

            if(!empty($userData['invite_uid'])){
                if($userData['invite_uid'] == $userInfo->id){
                    return redirect(env('APP_WEB_URL') . "/share?token={$token}&wid={$appid}");
                }
                if(
                    ActivityAnswer::where('ask_uid', $userData['invite_uid'])
                        ->where('make_uid', $userInfo->id)
                        ->first()
                ){
                    if(empty($userInfo->answer_goods_id)) {
                        return redirect(env('APP_WEB_URL') . "/index?token={$token}&wid={$appid}");
                    }else{
                        return redirect(env('APP_WEB_URL') . "/share?token={$token}&wid={$appid}");
                    }
                }else {
                    return redirect(env('APP_WEB_URL') . "/answer?askuid={$userData['invite_uid']}&token={$token}&wid={$appid}");
                }
            }elseif(empty($userInfo->answer_goods_id)) {
                return redirect(env('APP_WEB_URL') . "/index?token={$token}&wid={$appid}");
            }else{
                return redirect(env('APP_WEB_URL') . "/share?token={$token}&wid={$appid}");
            }
        }
    }


    public function openPlatformJsSdk($appid, Request $request){
        $apis = $request->input('apis');
        if($apis){
            $apis_arr = explode(',',$apis);
        }else{
            $apis_arr = ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareWeibo'];
        }

        $wechat = WechatOpenplatformToken::where('appid', $appid)->first();
        if(!$wechat){
            return response('登录失败');
        }
        $config = \Config::get('wechat.open_platform.default');
        $openPlatform = Factory::openPlatform($config);
        $wechatApp = $openPlatform->officialAccount($wechat->appid, $wechat->refresh_token);

        $js = $wechatApp->jssdk;

        $debug = true;
        if($request->has('debug')){
            $debug = $request->input('debug');
        }

        if($request->has('url')) {
            $js->setUrl($request->get('url'));
        }

        $config = $js->buildConfig($apis_arr, $debug, $beta = true, $json = true);
        if(!empty($config)){
            return response()->json(Message::setResponseInfo('SUCCESS', $config));
        }else{
            return response()->json(Message::setResponseInfo('FAILED'));
        }
    }
}
